import { load } from "/admin/util/LoadView.js";
load('userlist');

let editModal = new bootstrap.Modal(document.getElementById('editModal'))//modal的实例化
let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'))
let res = [] //存放用户列表
let updateid = 0;
let updatephotofile = ''

let render = async function () {
    res = await fetch('http://localhost:3000/users').then(res => res.json());
    // console.log(res);
    userlistbody.innerHTML = res.map(item => `
         <tr>
            <th scope="row">${item.username}</th>
            <td><img src="${item.photo}" style="width:40px;height:40px;border-radius: 50%;"></td>
            <td>
                <button type="button" data-id="${item.id}" class="btn btn-primary btn-sm btn-edit" ${item.default ? 'disabled' : ''}>编辑</button>
                <button type="button" data-id="${item.id}" class="btn btn-danger btn-sm btn-delete" ${item.default ? 'disabled' : ''}>删除</button>
            
            </td>
        </tr>
    `).join('');
}

document.querySelector('#userlistbody').onclick = function (evt) {
    updateid = evt.target.dataset.id;
    if (evt.target.className.includes('btn-edit')) {
        editModal.toggle();
        // console.log(evt.target.dataset.id)
        //也可以发fetch请求，但是要尽量减少请求次数
        let user = res.filter(item => item.id == updateid);//两个等于号。因为id是数字类型，而updateid是字符串类型
        // console.log(user);
        username.value = user[0].username;
        password.value = user[0].password;
        userintro.value = user[0].userintro;
        updatephotofile = user[0].photo;
    } else if (evt.target.className.includes('btn-delete')) {
        deleteModal.toggle();
    }
}

photofile.onchange = function (evt) {
    let reader = new FileReader()
    reader.readAsDataURL(evt.target.files[0])
    reader.onload = function (e) {
        updatephotofile = e.target.result
    }
}
editConfirm.onclick = async function () {
    await fetch(`http://localhost:3000/users/${updateid}`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username.value,
            password: password.value,
            userintro: userintro.value,
            photo: updatephotofile
        })
    }).then(res => res.json())
    console.log(updateid)
    editModal.toggle();
    render();//location.reload()全局刷新页面，render()局部刷新页面
}


deleteConfirm.onclick = async function () {
    await fetch(`http://localhost:3000/users/${updateid}`,{
        method:'DELETE'
    }).then(res => res.json())
    deleteModal.toggle();
    render()
}
render()